<?php
session_start();
if (!isset($_SESSION["userid"])) {
    header("Location: /login.html");
    usleep(2 * 1000000);
    exit;
} ?>
<html>
<head>
    <meta charset="UTF-8">
    <title>学生信息管理系统</title>
    <link rel="stylesheet" href="css/model.css">
</head>
<style>
    body {
        font-family: Arial, sans-serif;
        background-color: #f3f4f6;
        margin: 0;
        padding: 20px;
    }

    h1 {
        text-align: center;
        color: #333;
    }

    .wrapper {
        background-color: #fff;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    }

    .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }

    .login-info {
        font-size: 14px;
        color: #666;
    }

    .logout {
        background-color: #dc3545;
        color: white;
        border: none;
        border-radius: 5px;
        padding: 5px 10px;
        cursor: pointer;
        transition: background-color 0.3s;
        text-align: right;
    }

    .logout:hover {
        background-color: #c82333;
    }

    .search-fun {
        margin-bottom: 15px;
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }

    .search-fun input[type="text"] {
        padding: 10px;
        margin-right: 10px;
        border: 1px solid #ccc;
        border-radius: 5px;
    }

    .btn-add {
        background-color: lightskyblue;
        border: none;
        border-radius: 5px;
        padding: 10px 15px;
        cursor: pointer;
        transition: background-color 0.3s;
    }

    .btn-add:hover {
        background-color: deepskyblue;
    }

    .btn-query {
        background-color: yellowgreen;
        border: none;
        border-radius: 5px;
        padding: 10px 15px;
        cursor: pointer;
        transition: background-color 0.3s;
    }

    .btn-query:hover {
        background-color: limegreen;
    }

    #stu-content {
        width: 100%;
        border-collapse: collapse;
        margin: auto;
    }

    #stu-content th, #stu-content td {
        border: 1px solid #ccc;
        padding: 10px;
        text-align: center;
    }

    #stu-content th {
        background-color: #007bff;
        color: white;
    }

    #stu-content tr:nth-child(even) {
        background-color: #f9f9f9;
    }

    #info {
        text-align: center;
        margin-top: 20px;
    }

    .pagination {
        display: flex;
        justify-content: center;
        margin-top: 35px;
    }

    .pagination button {
        border: none;
        background-color: #007bff;
        color: white;
        padding: 8px 12px;
        margin: 0 5px;
        border-radius: 5px;
        cursor: pointer;
        transition: background-color 0.3s;
    }

    .pagination button:hover {
        background-color: #0056b3;
    }

    .pagination span {
        padding: 8px 12px;
        margin: 0 5px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #333;
    }

    .btn-edit {
        background-color: #ffc107;
        color: white;
        border: none;
        cursor: pointer;
    }

    .btn-edit:hover {
        background-color: #e0a800;
    }

    .btn-del {
        background-color: #dc3545;
        color: white;
        border: none;
        cursor: pointer;
    }

    .btn-del:hover {
        background-color: #c82333;
    }
</style>
<body>
<div class="wrapper">
    <h1>学生信息总览</h1>
    <div class="header">
        <div class="login-info">
            <p><strong><?php echo '系统运行时间：' . date('Y-m-d H:i:s'); ?></strong></p>
            <p><strong><?php echo '当前登录用户: ' . $_SESSION['username']; ?></strong>
                <button class="logout">退出</button>
            </p>
        </div>
    </div>
    <div class="search-fun">
        <form class="search-form">
            编号 <input type="text" placeholder="请输入编号" id="search-id" name="id">
            姓名 <input type="text" placeholder="请输入姓名" id="search-name" name="name">
            <input type="submit" class="btn-query" value="查询">
            <input type="reset" class="btn-query" value="重置">
            <button class="btn-add">新增</button>
        </form>
    </div>
    <template id="stu-list-head-template">
        <tr>
            <th>编号</th>
            <th>姓名</th>
            <th>性别</th>
            <th>年龄</th>
            <th>籍贯</th>
            <th>操作</th>
        </tr>
    </template>
    <template id="stu-list-template">
        <tr>
            <td class="id"></td>
            <td class="name"></td>
            <td class="sex"></td>
            <td class="age"></td>
            <td class="city"></td>
            <td class="operation">
                <button class="btn-edit">修改</button>
                <button class="btn-del">删除</button>
            </td>
        </tr>
    </template>

    <table id="stu-content">
    </table>
    <div id="info"></div>
    <div id="messageModel" class="modal">
        <div class="modal-content">
            <span class="close" id="closeModal">&times;</span>
            <p id="modalMessage">您确认删除吗？</p>
            <div class="button-container">
                <button class="button confirm-btn" id="confirmButton">确认</button>
            </div>
        </div>
    </div>

    <!-- 分页条 -->
    <div class="pagination">
        <button id="prevPage">上一页</button>
        <span id="pageInfo">第 1 页</span>
        <button id="nextPage">下一页</button>
        <span id="pageTotal">总计 2  条</span>
    </div>
</div>
<script src="js/common.js"></script>
<script type="text/javascript">

    function delAfterConfirm(id) {
        showModal('您确定要删除此项吗？', function () {
            delById(id);
            initTableHeader();
            listStuByPage();
        });
    }

    // 获取提示框
    const info = document.querySelector('#info');
    const pageTotal = document.querySelector('#pageTotal')
    const pageInfo = document.querySelector('#pageInfo')
    const prevPage = document.querySelector('#prevPage')
    const nextPage = document.querySelector('#nextPage')

    let cur = 1;
    let pageSize = 10;
    let total = 0;
    let totalPage = 0;


    window.onload = () => {
        research();
        const searchForm = document.querySelector(".search-form");
        const btnQuery = document.querySelector('.btn-query');
        const btnAdd = document.querySelector('.btn-add');
        const logOut = document.querySelector('.logout')

        prevPage.addEventListener('click', ev => {
            cur--;
            if (cur < 1) {
                cur = 1;
            }
            research()
        })

        nextPage.addEventListener('click', ev => {
            cur++;
            if (cur > totalPage) {
                cur = totalPage;
            }
            research()
        })


        searchForm.addEventListener('submit', evt => {
            evt.preventDefault();
        })


        // 为检索框绑定点击事件
        btnQuery.addEventListener('click', event => {
            research()
        })

        btnAdd.addEventListener('click', event => {
            window.location.href = 'add.php';
        })

        logOut.addEventListener('click', evt => {
            fetch(`dispatch.php?controller=StudentManage&service=logout`, {
                method: 'GET'
            }).then(res => {
                if (res.status === 200) {
                    window.location.href = '/login.html';
                }
            })
        })

    }

    const research = () => {
        initTableHeader();
        listStuByPage();
    }


    const delById = id => {
        if (id) {
            fetch(`dispatch.php?controller=StudentManage&service=delById&id=${id}`, {
                method: 'GET'
            })
        }
    }

    const initTableHeader = () => {
        // 清空原数据
        document.querySelector('#stu-content').innerHTML = '';
        info.innerHTML = '';
        // 追加表单头
        let studentHeaderTemplate = document.getElementById("stu-list-head-template");
        let stuContent = document.getElementById("stu-content");
        let head = studentHeaderTemplate.content.cloneNode(true);
        stuContent.appendChild(head);
    }

    // 分页检索学生信息
    const listStuByPage = () => {
        let id = document.querySelector('#search-id').value
        let name = document.querySelector('#search-name').value
        fetch(`dispatch.php?controller=StudentManage&service=listStudentInfoByPage&cur=${cur}&pageSize=${pageSize}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                id: id,
                name: name,
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.data) {
                    if (data.data instanceof Array) {
                        appendData(data);
                        cur = data.cur;
                        total = data.total;
                        totalPage = total % pageSize === 0 ? Math.floor(total / pageSize) : Math.ceil(total / pageSize);
                    } else {
                        resetPage();
                        appendEmptyData();
                    }
                } else {
                    resetPage();
                    appendEmptyData();
                }
                pageInfo.innerHTML = `第 ${cur} 页`;
                pageTotal.innerHTML = `总计 ${total}  条 ｜ ${totalPage} 页`;
            })
    }

    const resetPage = () => {
        total = 0;
        cur = 1;
        totalPage = 0;
    }

    // 追加子节点
    const appendData = (data) => {
        let stuContent = document.getElementById('stu-content');
        if (data.data && data.data instanceof Array) {
            // 如果存在列表
            let stuList = data.data
            let studentTemplate = document.getElementById('stu-list-template');
            if (stuList.length > 0) {
                stuList.forEach(stu => {
                    let newStudent = studentTemplate.content.cloneNode(true);
                    newStudent.querySelector(".id").textContent = stu.id;
                    newStudent.querySelector(".name").textContent = stu.name;
                    newStudent.querySelector(".sex").textContent = stu.sex;
                    newStudent.querySelector(".age").textContent = stu.age;
                    newStudent.querySelector(".city").textContent = stu.city;

                    newStudent.querySelector(".btn-del").addEventListener('click', event => {
                        delAfterConfirm(stu.id);
                    })

                    newStudent.querySelector(".btn-edit").addEventListener('click', event => {
                        window.location.href = `edit.php?id=${stu.id}`;
                    })

                    stuContent.appendChild(newStudent);
                });
            } else {
                appendEmptyData()
            }
        }
    }

    const appendEmptyData = () => {
        let infoElement = document.createElement('p');
        infoElement.textContent = '未检索到数据...';
        info.appendChild(infoElement);
    }

</script>
</body>
</html>
